﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace WriteForFighting.FightingAPI
{
    static class PlayerAssemblyLoader
    {
        public static Player GetPlayerInstanceFromAssembly(string filePath)
        {
            Assembly asm = Assembly.LoadFrom(filePath);
            Type[] types = asm.GetTypes();

            foreach (Type type in types)
            {
                if (type.BaseType.FullName == "WriteForFighting.FightingAPI.Player")
                {
                    IEnumerable<Attribute> attributes = type.GetCustomAttributes();

                    foreach (Attribute att in attributes)
                    {
                        if (att.GetType().Equals(new PlayerProgramAttribute().GetType()))
                        {
                            PlayerProgramAttribute playerAtt = GetPlayerInfo((Player)Activator.CreateInstance(type));
                            Console.WriteLine("\n'" + playerAtt.Name + "'が読み込まれました\n" +
                                              "Author: " + playerAtt.Author + "\n" +
                                              "Version: " + playerAtt.Version + "\n");
                            break;
                        }
                    }

                    return (Player)Activator.CreateInstance(type);
                }
            }

            throw new BadImageFormatException("これは、有効な機体プログラムではありません。\n" +
                                                "所定のクラスを実装したクラスが見つかりません。", filePath);
        }

        public static PlayerProgramAttribute GetPlayerInfo(Player player)
        {
            IEnumerable<Attribute> attributes = player.GetType().GetCustomAttributes();

            foreach (Attribute att in attributes)
            {
                if (att.GetType().Equals(new PlayerProgramAttribute().GetType()))
                {
                    return (PlayerProgramAttribute)att;
                }
            }

            return new PlayerProgramAttribute();
        }
    }
}
